﻿
//var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(sourceId) {
    var fileSize = 0;
    var filetypes = [".jpg", ".png", ".jpeg", ".bmp"];
    var filepath = document.getElementById(sourceId).value;
    var filemaxsize = 1024 * 2;//2M
    if (filepath) {
        var isnext = false;
        var fileend = filepath.substring(filepath.indexOf("."));
        if (filetypes && filetypes.length > 0) {
            for (var i = 0; i < filetypes.length; i++) {
                if (filetypes[i] == fileend) {
                    isnext = true;
                    break;
                }
            }
        }
        if (!isnext) {
            alert("请选择图片类型文件！");
            document.getElementById(sourceId).value = "";
            return false;
        }
    } else {
        return false;
    }
    //if (isIE && !document.getElementById(sourceId).files) {
    //    var filePath = document.getElementById(sourceId).value;
    //    var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
    //    if (!fileSystem.FileExists(filePath)) {
    //        alert("图片不存在，请重新选择！");
    //        return false;
    //    }
    //    var file = fileSystem.GetFile(filePath);
    //    fileSize = file.Size;
    //} else {
    //    fileSize = document.getElementById(sourceId).files[0].size;
    //    console.log(fileSize)
    //}

    var size = document.getElementById(sourceId).files[0].size / 1024;
    if (size > filemaxsize) {
        alert("图片大小不能大于" + filemaxsize / 1024 + "M！");
        document.getElementById(sourceId).value = "";
        return false;
    }
    if (size <= 0) {
        alert("图片大小不能为0！");
        document.getElementById(sourceId).value = "";
        return false;
    }
}
/**
* 从 file 域获取 本地图片 url
*/
function getFileUrl(sourceId) {
    var isimg = fileChange(sourceId);
    if (isimg == false) {
        return "";
    }
    var url;
    if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE
        url = document.getElementById(sourceId).value;
    } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    }

    return url;
}

/**
* 将本地图片 显示到浏览器上
*/
function preImg(sourceId, targetId, callback) {
    var url = getFileUrl(sourceId);
    var imgPre = document.getElementById(targetId);
    if (url) {
        if (callback) {       
            var id = $("#" + sourceId).attr("rel");
            callback(id);
        }
    } 
    imgPre.src = url;
}